
#include <signal.h>

#include <iostream>

using std::cout;
using std::endl;

#include <workflow/WFFacilities.h>
#include <workflow/WFHttpServer.h>
#include <workflow/HttpUtil.h>

static WFFacilities::WaitGroup waitGroup(1);

void sighandler(int num)
{
    printf("sig number %d is comming\n", num);
    waitGroup.done();
}

void httpCallback(WFHttpTask * serverTask)
{
    cout << "httpCallback is running" << endl;
    cout << "serverTask addr:" << serverTask << endl;
    auto resp = serverTask->get_resp();
    //2.2 添加首部字段
    resp->add_header_pair("Content-Type", "text/html");
    resp->add_header_pair("Server", "Workflow HttpServer");
    //2.3 添加消息体
    std::string msg("<html><body>welcome to workflow server</body></html>");
    resp->append_output_body(msg.c_str(), msg.size());
    resp->add_header_pair("Content-Length", std::to_string(msg.size()).c_str());
}

void process(WFHttpTask * serverTask)
{
    cout << "process is running" << endl;
    cout << "serverTask addr:" << serverTask << endl;
    //0. 设置serverTask的回调函数
    serverTask->set_callback(httpCallback);

    //1. 解析请求
    auto req = serverTask->get_req();
    printf("%s %s %s\n", req->get_method(),
           req->get_request_uri(),
           req->get_http_version());

    protocol::HttpHeaderCursor cursor(req);
    std::string key,value;
    while(cursor.next(key, value)) {
        cout << key << ": " << value << endl;
    }

    //2. 生成响应
    auto resp = serverTask->get_resp();
    //2.1 构造起始行
    resp->set_http_version("HTTP/1.1");
    resp->set_status_code("201");
    resp->set_reason_phrase("OK");
#if 0
    //2.2 添加首部字段
    resp->add_header_pair("Content-Type", "text/html");
    resp->add_header_pair("Server", "Workflow HttpServer");
    //2.3 添加消息体
    std::string msg("<html><body>welcome to workflow server</body></html>");
    resp->append_output_body(msg.c_str(), msg.size());
    resp->add_header_pair("Content-Length", std::to_string(msg.size()).c_str());
#endif

}

void test0()
{
    signal(SIGINT, sighandler);
    WFHttpServer server(process);

    if(server.start(8888) == 0) {
        waitGroup.wait();
        server.stop();//停止服务器
    } else {
        cout << "server start failed" << endl;
    }
}


int main()
{
    test0();
    return 0;
}

